package com.wei.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wei.entity.Order;
import com.wei.service.OrderService;
import com.wei.utils.JwtUtils;
import com.wei.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wjx
 * @ClassName OrderController
 * @description: TODO
 * @date 2022-12-04 05:00
 * @version: 1.0
 */
@RestController
@RequestMapping("/eduorder/payment")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 生成订单
     *
     * @param courseId
     * @param request
     * @return
     */
    @PostMapping("/createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request) {

        String uid = JwtUtils.getMemberIdByJwtToken(request);

        String orderNo = orderService.createOrderInfo(courseId, uid);

        return R.ok().data("orderNo", orderNo);
    }

    @GetMapping("/getOrderById/{orderNo}")
    public R getOrderById(@PathVariable String orderNo) {

        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderNo, orderNo);

        Order order = orderService.getOne(queryWrapper);

        return R.ok().data("order", order);
    }

    /**
     * 查询订单状态
     *
     * @param courseId
     * @param memberId
     * @return
     */
    @GetMapping("/queryPayStatus/{courseId}/{memberId}")
    public boolean queryPayStatus(@PathVariable String courseId, @PathVariable(required = false) String memberId) {

        if (courseId == null || memberId == null) {
            return false;
        }

        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Order::getCourseId, courseId).eq(Order::getMemberId, memberId).eq(Order::getStatus, 1);

        long count = orderService.count(queryWrapper);
//        System.out.println("======="+count);
        return count > 0;
    }

    @GetMapping("/buyCount/{courseId}")
    public Integer buyCount(@PathVariable String courseId) {


        //根据课程id和状态来统计购买数量
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Order::getCourseId, courseId).eq(Order::getStatus, 1);

        List<Order> orderList = orderService.list(queryWrapper);

        return orderList.size();
    }
}

